import 'package:dio/dio.dart';
import 'package:star_author/api/base_api.dart';
import 'package:loading_more_list/loading_more_list.dart';

import '../../utils/common_util/log_util.dart';

typedef List<T> ListBuilder<T>(List<dynamic> list);

class CommonPageLoadController<T> extends LoadingMoreBase<T> {
  CommonPageLoadController(
    this.baseApi,
    this.listBuilder, {
    this.count = 10,
    this.isStartLoad = true,
    this.requestCallback,
    this.handleResDataCallback,
    this.returnListLength,
  }) : super() {
    firstPageTimestamp = DateTime.now().millisecondsSinceEpoch;
  }

  BaseApi baseApi;

  ListBuilder<T> listBuilder;

  int count;

  int totalCount = 0;

  //是否立即加载
  bool isStartLoad;

  int _pageIndex = 1;

  Function? requestCallback;

  Function? handleResDataCallback;

  Function? returnListLength;

  bool _hasMore = true;

  bool forceRefresh = false;

  int get pageIndex {
    return _pageIndex;
  }

  late int firstPageTimestamp;

  @override
  bool get hasMore {
    return _hasMore;
  }

  @override
  Future<bool> refresh([bool clearBeforeRequest = false]) async {
    ///下拉刷新重置时间戳
    firstPageTimestamp = DateTime.now().millisecondsSinceEpoch;

    _hasMore = true;
    _pageIndex = 1;

    bool result = await super.refresh(clearBeforeRequest);
    return result;
  }

  @override
  Future<bool> loadData([bool isLoadMoreAction = false]) async {
    LogUtil.v("loadData");
    bool isSuccess = false;
    try {
      baseApi
        ..requestParams['per_page'] = count.toString()
        ..requestParams['page'] = _pageIndex.toString()
        ..requestParams['first_page_timestamp'] = firstPageTimestamp.toString();
    } catch (e) {
      LogUtil.v("e:$e");
    }

    if (isStartLoad) {
      try {
        Response response = await baseApi.send();

        if (response.statusCode != 200) {
          _hasMore = false;
          isSuccess = true;
        } else {
          List<dynamic> dataList = [];

          if (response.data["data"] != null) {
            dataList =  response.data["data"] ?? [];
          }

          if (_pageIndex == 1) {
            clear();
          }

          if (returnListLength != null) {
            returnListLength!(response.data);
          }

          ///处理Response data
          if (handleResDataCallback == null) {
            addAll(listBuilder(dataList));
          } else {
            List<dynamic> resultList = [];
            resultList = handleResDataCallback!(dataList);

            addAll(listBuilder(resultList));
          }

          if (dataList.length == count) {
            _hasMore = true;
          } else {
            _hasMore = false;
          }
          _pageIndex++;
          isSuccess = true;

          totalCount = response.data?['meta']?['total_count'] ?? 0;
        }
      } catch (e, t) {
        LogUtil.v(e);
        LogUtil.v(t);
        isSuccess = false;
      }
    } else {
      isStartLoad = false;
      isSuccess = true;
    }

    if (requestCallback != null) {
      requestCallback!(isSuccess);
    }
    return isSuccess;
  }
}
